/**
 * 152. 乘积最大子数组
 * https://leetcode-cn.com/problems/maximum-product-subarray/
 */

/**
 * @param {number[]} nums
 * @return {number}
 */
function maxProduct(nums) {
  let max = -Infinity;
  let preMax = 1;
  let preMin = 1;
  for (let i = 0; i < nums.length; i += 1) {
    const newMax = nums[i] * preMax;
    const newMin = nums[i] * preMin;
    preMax = Math.max(newMax, newMin, nums[i]);
    preMin = Math.min(newMax, newMin, nums[i]);
    max = Math.max(max, preMax);
  }
  return max;
}

console.log(maxProduct([2, 3, -2, 4]) === 6);
console.log(maxProduct([-2, 0, -1]) === 0);
console.log(maxProduct([-2, 3, -4]) === 24);
console.log(maxProduct([-3, -1, -1]) === 3);
